﻿using Microsoft.EntityFrameworkCore;
using XsqTech.SmartOA.Dtos.DTO;
using XsqTech.SmartOA.IRespository.Base;

namespace XsqTech.SmartOA.EFCore.Respository.Base
{
    public class BaseRespository<T> : IBaseRespository<T> where T : class, new()
    {
        //不能写死，注入基类
        DbContext _db;

        public BaseRespository(DbContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 泛型添加
        /// </summary>
        /// <param name="m"></param>
        public void Add(T m)
        {
            _db.Set<T>().Add(m);
        }
        /// <summary>
        /// 泛型显示
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> Query()
        {
            return _db.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 泛型删除（单删）
        /// </summary>
        /// <param name="id"></param>
        public void Delete(object id)
        {
           var m = _db.Set<T>().Find(id);
           this._db.Remove(m);
        }
        /// <summary>
        /// 泛型删除（批删）
        /// </summary>
        /// <param name="list"></param>
        public void AllDelete(List<object> list)
        {
            list.ForEach(x =>
            {
                this.Delete(x);
            });
        }
        /// <summary>
        /// 泛型修改
        /// </summary>
        /// <param name="m"></param>
        public void Update(T m)
        {
            _db.Set<T>().Update(m);
        }
        public int Upt(UptDepartmentsDto model)
        {
            _db.Database.ExecuteSqlRaw($"update Department set Name='{model.Name}' where DepId ={model.DepId}");
            return _db.SaveChanges();
        }
        /// <summary>
        /// 根据主键获取对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetById(Guid id)
        {
            if (id == null) throw new ArgumentNullException();

            return _db.Set<T>().Find(id)!;
        }
        /// <summary>
        /// 根据主键获取对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetBysId(object id)
        {
            if (id == null) throw new ArgumentNullException();

            return _db.Set<T>().Find(id)!;
        }
    }
}